package Presenter;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import Models.POSProductServingType;
import Models.POSTasterTray;

public class POSTasterTrayPresenter extends AbstractPresenter<POSTasterTray> {
	final String SINGLEITEM = "posTasterTray";
	final String MULTIITEM = "pOSTasterTrays";
	
	public ArrayList<POSTasterTray> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public POSTasterTray tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public POSTasterTray createItemFromJSONObject(JSONObject jsonTray){
		POSTasterTray tray = new POSTasterTray();
		try{
			tray.setId(jsonTray.getInt("id"));
			tray.setTrayPrice(jsonTray.getDouble("trayPrice"));
			//Set POSProductServingTypeCollection.
			ArrayList<POSProductServingType> trayItems = new ArrayList<POSProductServingType>();
			if(!jsonTray.isNull("servingTypeCollection")){
				Object item = jsonTray.get("servingTypeCollection");
				POSProductServingTypePresenter pstPresenter = new POSProductServingTypePresenter();
				if(item instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)item;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonLineItem = jPSTArray.getJSONObject(i);
						trayItems.add(pstPresenter.createItemFromJSONObject(jsonLineItem));
					}
				} else {
					JSONObject jsonLineItem = (JSONObject)item;
					trayItems.add(pstPresenter.createItemFromJSONObject(jsonLineItem));
				}
				tray.setProducts(trayItems);
			}
			return tray;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(POSTasterTray item){
		try{
			JSONObject json = new JSONObject();
			json.put("id", item.getId());
			json.put("trayPrice", item.getTrayPrice());
			if(item.getProducts()!=null){
				POSProductServingTypePresenter trayPresenter = new POSProductServingTypePresenter();
				if(item.getProducts().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getProducts().size(); i++){
						jsonArray.put(trayPresenter.createJSON(item.getProducts().get(i)));
					}
					json.put("servingTypeCollection", jsonArray);
				}
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSTasterTray getEmptyEntity(){
		POSTasterTray entity = new POSTasterTray();
		return entity;
	}
}
